import CanvasTools from "@/components/SmartCanvasWidget/CanvasTools";
import {Application, Assets, Container, Graphics, Rectangle, Sprite, Texture} from "pixi.js";

/**
 * 快速选区类
 * */
class CanvasDistrict
{
    // 当前对象
    private static instance: CanvasDistrict;

    // 当前快速选区容器对象
    private static districtContainer: Container<any>;

    // 工具
    private static tools: any;

    // 实例
    private static app: Application;

    // 当前是否激活
    private static enable: boolean = true;

    // 当前激活时的层级
    private static zIndex: number = 999;

    // 当前未激活时的层级
    private static zIndexUnable: number = 0;

    // 当前激活状态的透明度
    private static alphaActive: number = 0.6;

    // 当前鼠标移入时的透明度
    private static alphaHover: number = 0.8;

    /**
     * 构造函数
     * @param {Object} argumentsList 参数列表 {app(对象): Application; options(配置): Record<string, any>}
     * */
    constructor(argumentsList: Record<string, any>)
    {
        // 实例
        CanvasDistrict.app = argumentsList.app;

        // 实例化工具
        CanvasDistrict.tools = new CanvasTools({
            app: argumentsList.app
        });

        // 当前对象
        CanvasDistrict.instance = this;
    }

    /**
     * 快速选区
     * */
    district(): void
    {
        // 获取重绘容器
        const drawContainer = CanvasDistrict.tools.getApplicationSourceData(CanvasDistrict.app.stage, "drawing-district-container") as Container<any>;

        if (!drawContainer)
        {
            // 初始化快速选区
            this.initDistrict();
        }
    }

    // 模拟快速选区
    districtDemo(urls: string[]): void
    {
        // 获取重绘容器
        const drawContainer = CanvasDistrict.tools.getApplicationSourceData(CanvasDistrict.app.stage, "drawing-district-container") as Container<any>;

        if (!drawContainer)
        {
            // 获取画板资源容器（存放背景图等基础元素）
            const boardContainer = CanvasDistrict.tools.getApplicationSourceData(CanvasDistrict.app.stage, "drawing-board-assets-container") as Container<any>;

            if (!boardContainer)
            {
                return;
            }

            // 获取扩展层
            const extendContainer = CanvasDistrict.tools.getApplicationSourceData(CanvasDistrict.app.stage, "image-extend-container") as Container<any>;

            if (!extendContainer)
            {
                return;
            }

            // 获取容器中的子元素（通常第一个元素是背景图）
            const children: any[] = boardContainer.children;

            if (!children || !children.length)
            {
                return;
            }

            // 获取底层背景图精灵对象（作为画布底板）
            const backgroundImage = children[0] as Sprite;

            if (!backgroundImage)
            {
                return;
            }

            // 当前的图片地址
            const imageUrl = backgroundImage.texture.source?._sourceOrigin;

            if (!imageUrl)
            {
                return;
            }

            // 初始化遮罩图
            initMask(extendContainer, backgroundImage, urls);
        }

        // 初始化遮罩图
        function initMask(extendContainer: Container<any>, backgroundImage: Sprite, urls: string[]): void
        {
            // 创建绘制层容器（用于承载绘制层和临时绘图对象）
            const spriteContainer = new Container();

            // 对齐背景图位置
            spriteContainer.position.set(backgroundImage.x, backgroundImage.y);

            // 设置别名
            spriteContainer.label = "drawing-district-container";

            // 当前背景精灵做为蒙版
            spriteContainer.mask = new Sprite(CanvasDistrict.tools.createGridTexture({width: backgroundImage.width, height: backgroundImage.height, gap: 16}));

            // 设置当前激活时的层级
            spriteContainer.zIndex = CanvasDistrict.zIndex;

            // 缓存当前快速选区容器对象
            CanvasDistrict.districtContainer = spriteContainer;

            // 当前通道图片资源集合
            let maskAssetsList: string[] = [];

            // 加载遮罩资源
            urls.forEach((url: string, index: number) =>
            {
                // 缓存资源名称
                maskAssetsList.push(`mask${index}`);

                Assets.add([{alias: `mask${index}`, src: url, data: {crossOrigin: "anonymous"}}]);
            });

            // 获取通道图资源
            Assets.load(maskAssetsList).then(async (maskTextures: Record<string, any>) =>
            {
                // 获取当前图片的坐标以及渲染尺寸
                const {x, y, width: renderWidth, height: renderHeight} = backgroundImage || {};

                // 获取当前图片实际的宽高
                const {width, height} = backgroundImage.texture.source;

                // 计算缩放比
                const scale = Math.min(width / renderWidth, height / renderHeight);

                // 将遮罩层应用在画板上
                for (const maskKey in maskTextures)
                {
                    if (maskKey.includes("mask"))
                    {
                        // 渲染精灵图层
                        const maskSprite = CanvasDistrict.instance.renderSpriteLayer({
                            texture: maskTextures[maskKey],
                            x,
                            y,
                            width,
                            height
                        });

                        // 获取遮罩纹理
                        const textureMask = await CanvasDistrict.instance.getMaskTexture({
                            texture: maskSprite.texture,
                            width,
                            height
                        });

                        // 创建遮罩纹理层
                        const maskTextureSprite = CanvasDistrict.instance.createMaskLayer({
                            texture: textureMask.texture,
                            width: renderWidth,
                            height: renderHeight,
                            sourceWidth: width,
                            sourceHeight: height,
                            source: textureMask.source,
                            canvas: textureMask.canvas,
                            label: maskKey,
                            scale: scale,
                            alpha: 0
                        });

                        // 将遮罩添加到容器
                        spriteContainer.addChild(maskTextureSprite);
                    }
                }

                // 设置容器事件模式
                spriteContainer.eventMode = "static";

                // 设置容器的 hitArea
                spriteContainer.hitArea = new Rectangle(0, 0, renderWidth, renderHeight);

                // 监听鼠标事件
                spriteContainer.on("pointerdown", (event: Record<string, any>) =>
                {
                    // 绘制未激活时，阻止冒泡
                    if (!CanvasDistrict.enable)
                    {
                        // 阻止事件冒泡
                        event.stopPropagation();

                        return;
                    }

                    // 获取鼠标相对容器的位置
                    const {x, y} = CanvasDistrict.tools.getMouseLocalPos({
                        event: event,
                        container: spriteContainer
                    });

                    // 检查坐标是否在显示纹理范围内
                    if (x < 0 || x >= renderWidth || y < 0 || y >= renderHeight)
                    {
                        return;
                    }

                    // 自定义事件冒泡处理
                    CanvasDistrict.instance.customEventBubbling({event, container: spriteContainer, scale: scale, localPos: {x, y}}, (argumentsList: Record<string, any>) =>
                    {
                        const {container, active} = argumentsList || {};

                        // 切换激活状态
                        container.metadata.active = !active;

                        // 找到当前遮罩
                        const currentSprite = container.children?.find((itemChild: Sprite | Graphics) =>
                        {
                            return itemChild.label && itemChild.label.includes(`graphics-${container.label}`);
                        });

                        if (currentSprite)
                        {
                            // 清除当前通道信息
                            currentSprite.clear();

                            if (container.metadata.active)
                            {
                                currentSprite.rect(0, 0, renderWidth, renderHeight).fill({color: 0xffffff, alpha: CanvasDistrict.alphaHover});
                            }
                        }
                    });

                }).on("pointermove", (event: Record<string, any>) =>
                {
                    // 绘制未激活时，阻止冒泡
                    if (!CanvasDistrict.enable)
                    {
                        // 阻止事件冒泡
                        event.stopPropagation();

                        return;
                    }

                    // 获取鼠标相对容器的位置
                    const {x, y} = CanvasDistrict.tools.getMouseLocalPos({
                        event: event,
                        container: spriteContainer
                    });

                    // 检查坐标是否在纹理范围内
                    if (x < 0 || x >= renderWidth || y < 0 || y >= renderHeight)
                    {
                        return;
                    }

                    // 自定义事件冒泡处理
                    CanvasDistrict.instance.customEventBubbling({event, container: spriteContainer, scale: scale, localPos: {x, y}}, (argumentsList: Record<string, any>) =>
                    {
                        const {label} = argumentsList || {};

                        // 当前父级的子集
                        const children = spriteContainer.children;

                        // 遍历子集
                        children.forEach((item: Container<any> | Sprite) =>
                        {
                            // 过滤遮罩
                            if (item.label.includes("mask"))
                            {
                                // // 找到当前遮罩
                                const currentSprite = item.children?.find((itemChild: Sprite | Graphics) =>
                                {
                                    return itemChild.label && itemChild.label.includes(`graphics-${item.label}`);
                                });

                                if (currentSprite)
                                {
                                    // 清除当前通道信息
                                    currentSprite.clear();

                                    // 获取当前遮罩是否激活
                                    const active = (item as any)?.metadata?.active;

                                    // 判断当前通道是否激活
                                    if (active)
                                    {
                                        currentSprite.rect(0, 0, renderWidth, renderHeight).fill({color: 0xffffff, alpha: CanvasDistrict.alphaActive});
                                    }

                                    if (item.label === label)
                                    {
                                        // 清除当前通道信息
                                        currentSprite.clear();

                                        currentSprite.rect(0, 0, renderWidth, renderHeight).fill({color: 0xffffff, alpha: CanvasDistrict.alphaHover});
                                    }
                                }
                            }
                        });
                    });

                }).on("pointerleave", (event: Record<string, any>) =>
                {
                    // 绘制未激活时，阻止冒泡
                    if (!CanvasDistrict.enable)
                    {
                        // 阻止事件冒泡
                        event.stopPropagation();

                        return;
                    }

                    // 当前父级的子集
                    const children = spriteContainer.children;

                    // 遍历子集
                    children.forEach((item: Container<any> | Sprite) =>
                    {
                        // 过滤遮罩
                        if (item.label.includes("mask"))
                        {
                            // 找到当前遮罩
                            const currentSprite = item.children?.find((itemChild: Sprite | Graphics) =>
                            {
                                return itemChild.label && itemChild.label.includes(`graphics-${item.label}`);
                            });

                            if (currentSprite)
                            {
                                // 清除当前通道信息
                                currentSprite.clear();

                                // 获取当前遮罩是否激活
                                const active = (item as any)?.metadata?.active;

                                // 判断当前通道是否激活
                                if (active)
                                {
                                    currentSprite.rect(0, 0, renderWidth, renderHeight).fill({alpha: CanvasDistrict.alphaActive});
                                }
                            }
                        }
                    });
                });

            }).finally(() => {
                // 添加到画板层级结构中
                extendContainer.addChild(spriteContainer);
            });
        }
    }

    /**
     * 禁用画笔
     * */
    disable(): void
    {
        // 设置画笔未激活
        CanvasDistrict.enable = false;

        // 设置当前快速选区容器对象的层级
        if (CanvasDistrict.districtContainer)
        {
            CanvasDistrict.districtContainer.zIndex = CanvasDistrict.zIndexUnable;
        }
    }

    /**
     * 启用画笔
     * */
    enable(): void
    {
        // 设置画笔激活
        CanvasDistrict.enable = true;

        // 设置当前快速选区容器对象的层级
        if (CanvasDistrict.districtContainer)
        {
            CanvasDistrict.districtContainer.zIndex = CanvasDistrict.zIndex;
        }
    }

    /**
     * 初始化快速选区
     * */
    private initDistrict(): void
    {
        // 获取画板资源容器（存放背景图等基础元素）
        const boardContainer = CanvasDistrict.tools.getApplicationSourceData(CanvasDistrict.app.stage, "drawing-board-assets-container") as Container<any>;

        if (!boardContainer)
        {
            return;
        }

        // 获取容器中的子元素（通常第一个元素是背景图）
        const children: any[] = boardContainer.children;

        if (!children || !children.length)
        {
            return;
        }

        // 获取底层背景图精灵对象（作为画布底板）
        const backgroundImage = children[0] as Sprite;

        if (!backgroundImage)
        {
            return;
        }

        // 当前的图片地址
        const imageUrl = backgroundImage.texture.source?._sourceOrigin;

        if (!imageUrl)
        {
            return;
        }

        // 通过当前图片地址，获取通道图
        smartSplice({urls: [imageUrl], num: 1}).then((res: Record<string, any>) =>
        {
            const {code, data: {urls = []}, message} = res || {};

            if (code === 200)
            {
                if (isArray(urls) && !isEmpty(urls))
                {
                    initMask(backgroundImage, urls);
                }
                else
                {
                    ElMessage.error("通道图获取失败");
                }
            }
            else
            {
                ElMessage.error(message);
            }

        }).catch((error: Record<string, any>) =>
        {
            const {data: {message = ""}} = error || {};

            // 错误提示
            ElMessage.error(message);
        });

        // 初始化遮罩图
        function initMask(texture: Sprite, urls: string[]): void
        {
            // 创建绘制层容器（用于承载绘制层和临时绘图对象）
            const spriteContainer = new Container();

            // 对齐背景图位置
            spriteContainer.position.set(backgroundImage.x, backgroundImage.y);

            // 设置别名
            spriteContainer.label = "drawing-district-container";

            // 当前背景精灵做为蒙版
            spriteContainer.mask = new Sprite(CanvasDistrict.tools.createGridTexture({width: texture.width, height: texture.height, gap: 16}));

            // 添加到画板层级结构中
            boardContainer.addChild(spriteContainer);

            // 当前通道图片资源集合
            let maskAssetsList: string[] = [];

            // 加载遮罩资源
            urls.forEach((url: string, index: number) =>
            {
                // 缓存资源名称
                maskAssetsList.push(`mask${index}`);

                Assets.add([{alias: `mask${index}`, src: url, data: {crossOrigin: "anonymous"}}]);
            });

            // 获取通道图资源
            Assets.load(maskAssetsList).then(async (maskTextures: Record<string, any>) =>
            {
                // 获取当前图片的坐标以及渲染尺寸
                const {x, y, width: renderWidth, height: renderHeight} = texture || {};

                // 获取当前图片实际的宽高
                const {width, height} = texture.texture.source;

                // 计算缩放比
                const scale = Math.min(width / renderWidth, height / renderHeight);

                // 将遮罩层应用在画板上
                for (const maskKey in maskTextures)
                {
                    if (maskKey.includes("mask"))
                    {
                        // 渲染精灵图层
                        const maskSprite = CanvasDistrict.instance.renderSpriteLayer({
                            texture: maskTextures[maskKey],
                            x,
                            y,
                            width,
                            height
                        });

                        // 获取遮罩纹理
                        const textureMask = await CanvasDistrict.instance.getMaskTexture({
                            texture: maskSprite.texture,
                            width,
                            height
                        });

                        // 创建遮罩纹理层
                        const maskTextureSprite = CanvasDistrict.instance.createMaskLayer({
                            texture: textureMask.texture,
                            width: renderWidth,
                            height: renderHeight,
                            sourceWidth: width,
                            sourceHeight: height,
                            source: textureMask.source,
                            canvas: textureMask.canvas,
                            label: maskKey,
                            scale: scale,
                            alpha: 0
                        });

                        // 将遮罩添加到容器
                        spriteContainer.addChild(maskTextureSprite);
                    }
                }

                // 设置容器事件模式
                spriteContainer.eventMode = "static";

                // 设置容器的 hitArea
                spriteContainer.hitArea = new Rectangle(0, 0, renderWidth, renderHeight);

                // 监听鼠标事件
                spriteContainer.on("pointerdown", (event: Record<string, any>) =>
                {
                    // 获取鼠标相对容器的位置
                    const {x, y} = CanvasDistrict.tools.getMouseLocalPos({
                        event: event,
                        container: spriteContainer
                    });

                    // 检查坐标是否在显示纹理范围内
                    if (x < 0 || x >= renderWidth || y < 0 || y >= renderHeight)
                    {
                        return;
                    }

                    // 自定义事件冒泡处理
                    CanvasDistrict.instance.customEventBubbling({event, container: spriteContainer, scale: scale, localPos: {x, y}}, (argumentsList: Record<string, any>) =>
                    {
                        const {container, active} = argumentsList || {};

                        // 切换激活状态
                        container.metadata.active = !active;

                        // 找到当前遮罩
                        const currentSprite = container.children?.find((itemChild: Sprite | Graphics) =>
                        {
                            return itemChild.label && itemChild.label.includes(`graphics-${container.label}`);
                        });

                        if (currentSprite)
                        {
                            // 清除当前通道信息
                            currentSprite.clear();

                            if (container.metadata.active)
                            {
                                currentSprite.rect(0, 0, renderWidth, renderHeight).fill({color: 0xffffff, alpha: 0.6});
                            }
                        }
                    });

                }).on("pointermove", (event: Record<string, any>) =>
                {
                    // 获取鼠标相对容器的位置
                    const {x, y} = CanvasDistrict.tools.getMouseLocalPos({
                        event: event,
                        container: spriteContainer
                    });

                    // 检查坐标是否在纹理范围内
                    if (x < 0 || x >= renderWidth || y < 0 || y >= renderHeight)
                    {
                        return;
                    }

                    // 自定义事件冒泡处理
                    CanvasDistrict.instance.customEventBubbling({event, container: spriteContainer, scale: scale, localPos: {x, y}}, (argumentsList: Record<string, any>) =>
                    {
                        const {label} = argumentsList || {};

                        // 当前父级的子集
                        const children = spriteContainer.children;

                        // 遍历子集
                        children.forEach((item: Container<any> | Sprite) =>
                        {
                            // 过滤遮罩
                            if (item.label.includes("mask"))
                            {
                                // // 找到当前遮罩
                                const currentSprite = item.children?.find((itemChild: Sprite | Graphics) =>
                                {
                                    return itemChild.label && itemChild.label.includes(`graphics-${item.label}`);
                                });

                                if (currentSprite)
                                {
                                    // 清除当前通道信息
                                    currentSprite.clear();

                                    // 获取当前遮罩是否激活
                                    const active = (item as any)?.metadata?.active;

                                    // 判断当前通道是否激活
                                    if (active)
                                    {
                                        currentSprite.rect(0, 0, renderWidth, renderHeight).fill({color: 0xffffff, alpha: 0.4});
                                    }

                                    if (item.label === label)
                                    {
                                        // 清除当前通道信息
                                        currentSprite.clear();

                                        currentSprite.rect(0, 0, renderWidth, renderHeight).fill({color: 0xffffff, alpha: 0.6});
                                    }
                                }
                            }
                        });
                    });

                }).on("pointerleave", () =>
                {
                    // 当前父级的子集
                    const children = spriteContainer.children;

                    // 遍历子集
                    children.forEach((item: Container<any> | Sprite) =>
                    {
                        // 过滤遮罩
                        if (item.label.includes("mask"))
                        {
                            // 找到当前遮罩
                            const currentSprite = item.children?.find((itemChild: Sprite | Graphics) =>
                            {
                                return itemChild.label && itemChild.label.includes(`graphics-${item.label}`);
                            });

                            if (currentSprite)
                            {
                                // 清除当前通道信息
                                currentSprite.clear();

                                // 获取当前遮罩是否激活
                                const active = (item as any)?.metadata?.active;

                                // 判断当前通道是否激活
                                if (active)
                                {
                                    currentSprite.rect(0, 0, renderWidth, renderHeight).fill({alpha: 0.6});
                                }
                            }
                        }
                    });
                });
            });
        }
    }

    /**
     * 渲染精灵图层
     * @param {Object} argumentsList 渲染参数（texture: 遮罩图资源; x: 遮罩图x坐标; y: 遮罩图y坐标; width: 遮罩图宽度; height: 遮罩图高度;）
     * @return {Object} Sprite
     * */
    private renderSpriteLayer(argumentsList: Record<string, any>): Sprite
    {
        const {texture, x, y, width, height} = argumentsList || {};

        // 创建精灵图层
        const sprite = Sprite.from(texture);

        // 设置精灵尺寸
        sprite.setSize(width, height);

        // 设置精灵位置
        sprite.position.set(x, y);

        return sprite;
    }

    /**
     * 获取遮罩层纹理
     * @param {Object} argumentsList 渲染参数（texture: 遮罩图资源; width: 遮罩图宽度; height: 遮罩图高度;）
     * */
    private getMaskTexture(argumentsList: Record<string, any>): Promise<{texture: Texture; source: ImageData | null, canvas: HTMLCanvasElement | null}>
    {
        return new Promise<{texture: Texture; source: ImageData | null, canvas: HTMLCanvasElement | null}>(resolve =>
        {
            const {texture, width, height} = argumentsList || {};

            // 获取遮罩层像素数据
            this.getMaskPixelData({
                texture,
                width,
                height
            }).then((pixelsMask: number[][]) =>
            {
                const currentTexture = this.createMaskTexture({
                    pixels: pixelsMask,
                    width,
                    height
                });

                resolve(currentTexture);

            }).catch((error: any) =>
            {
                // eslint-disable-next-line no-console
                console.error(error);

                // 创建当前空纹理，防止出错
                resolve({
                    texture: new Texture(),
                    source: null,
                    canvas: null
                });
            });
        });
    }

    /**
     * 获取遮罩层像素数据
     * @param {Object} argumentsList 渲染参数（texture: 遮罩图资源; width: 遮罩图宽度; height: 遮罩图高度;）
     * @return {number[][]} 遮罩层像素数据
     * */
    private getMaskPixelData(argumentsList: {texture: Texture; width: number; height: number}): Promise<number[][]>
    {
        return new Promise<number[][]>(resolve =>
        {
            const {texture, width, height} = argumentsList || {};

            // 创建临时应用
            const currentApp = new Application();

            // 初始化
            currentApp.init({
                // 画布尺寸
                width: width,
                // 画布尺寸
                height: height,
                // 背景alpha
                backgroundAlpha: 0,
                // 抗锯齿
                antialias: false,
                // 自动渲染
                autoStart: false,
                // 自动缩放
                autoDensity: false,
                // 分辨率（这里一定要是1，才能获取原始尺寸大小的图片）
                resolution: 1,
                // 每次渲染前清除画布
                clearBeforeRender: true
            }).then(() =>
            {
                // 创建临时精灵
                const tempSprite = new Sprite(texture);

                // 设置精灵尺寸
                tempSprite.setSize(width, height);

                // 加入渲染树并强制渲染
                currentApp.stage.addChild(tempSprite);

                // 使用目标尺寸渲染
                currentApp.renderer.resize(width, height);

                // 关键！触发实际渲染
                currentApp.renderer.render(currentApp.stage);

                // 获取画布
                const canvas = currentApp.renderer.extract.canvas(tempSprite) as HTMLCanvasElement;

                if (canvas)
                {
                    // 获取上下文
                    const context = canvas.getContext("2d", {willReadFrequently: true});

                    // 判断上下文是否存在
                    if (!context)
                    {
                        return [];
                    }

                    // 获取图像数据
                    const imageData = context.getImageData(0, 0, width, height);

                    // 获取像素数据
                    const data = imageData.data;

                    // 像素数据
                    const whitePixels: number[][] = [];

                    // 遍历像素数据
                    for (let y = 0; y < height; y++)
                    {
                        for (let x = 0; x < width; x++)
                        {
                            const index = (y * width + x) * 4;

                            // 如果判断 > 245会有很多图片噪点，对于框选区域不是很准确
                            // if (data[index] > 245 && data[index + 1] > 245 && data[index + 2] > 245 && data[index + 3] > 245) {
                            //   whitePixels.push([x, y]);
                            // }

                            if (data[index] > 1 && data[index + 1] > 1 && data[index + 2] > 1 && data[index + 3] > 1)
                            {
                                whitePixels.push([x, y]);
                            }
                        }
                    }

                    // 销毁临时精灵
                    tempSprite.destroy();

                    // 销毁临时实例
                    currentApp.destroy(true);

                    resolve(whitePixels);
                }
                else
                {
                    resolve([]);
                }
            }).catch((error: any) =>
            {
                // eslint-disable-next-line no-console
                console.error(error);

                resolve([]);
            });
        });
    }

    /**
     * 创建蒙版纹理
     * @param {Object} argumentsList 渲染参数（pixels: 像素数据; width: 遮罩图宽度; height: 遮罩图高度;）
     * @return {Texture} 蒙版纹理
     * */
    private createMaskTexture(argumentsList: {pixels: number[][]; width: number; height: number}): {texture: Texture, source: ImageData, canvas: HTMLCanvasElement}
    {
        const {pixels, width, height} = argumentsList || {};

        // 创建画布
        const canvas = document.createElement("canvas");

        // 设置画布宽
        canvas.width = width;

        // 设置画布高
        canvas.height = height;

        // 获取画布上下文
        const ctx = canvas.getContext("2d", {willReadFrequently: true})!;

        // 绘制白色区域
        const imageData = ctx.createImageData(width, height);

        // 遍历像素数据
        pixels.forEach(([x, y]) =>
        {
            // 设置像素数据
            const idx = (y * width + x) * 4;

            // 设置像素颜色
            imageData.data.set([255, 255, 255, 255], idx);
        });

        // 将像素数据绘制到画布上
        ctx.putImageData(imageData, 0, 0);

        return {
            texture: Texture.from(canvas),
            source: imageData,
            canvas
        };
    }

    /**
     * 创建遮罩纹理层
     * @param {Object} argumentsList 渲染参数（texture: 遮罩图; width: 遮罩图宽度; height: 遮罩图高度; label: 遮罩图标签; sourceWidth: 遮罩图源宽度; sourceHeight: 遮罩图源高度; source: 遮罩图像素数据源; canvas: 遮罩图画布; scale: 遮罩图缩放比; alpha: 遮罩图透明度;）
     * @return {Container} 遮罩纹理层
     * */
    private createMaskLayer(argumentsList: Record<string, any>): Container<any>
    {
        const {texture = {}, width = 0, height = 0, label = "", source = [], canvas, scale = 0, alpha = 0} = argumentsList || {};

        // 创建当前容器
        const container = new Container();

        // 设置别名
        container.label = label;

        // 设置自定义属性
        (container as any).metadata = {
            canvas: canvas, // 当前画布
            source: source, // 当前画布源
            scale: scale, // 当前缩放比
            active: false // 当前是否激活
        };

        // 创建遮罩图
        const imageToReveal = new Graphics();

        // 设置别名
        imageToReveal.label = `graphics-${label}`;

        // 填充遮罩图
        imageToReveal.rect(0, 0, width, height).fill({alpha: alpha});

        // 创建精灵
        const renderTextureSprite = new Sprite(texture);

        // 设置标签
        renderTextureSprite.label = `sprite-${label}`;

        // 设置遮罩图尺寸
        renderTextureSprite.setSize(width, height);

        // 将当前精灵添运用到遮罩图
        imageToReveal.mask = renderTextureSprite;

        // 将遮罩添加到容器
        container.addChild(imageToReveal, renderTextureSprite);

        return container;
    }

    /**
     * 自定义事件冒泡处理
     * @param {Object} argumentsList 渲染参数（container: 容器; scale: 遮罩图缩放比; localPos: 鼠标位置;）
     * @param {Function} fn 事件冒泡处理函数
     * */
    private customEventBubbling(argumentsList: Record<string, any>, fn: Function): void
    {
        const {container, scale = 1, localPos = {}} = argumentsList || {};

        // 当前父级的子集
        const children = container.children;

        children.forEach((item: Container<any> | Sprite) =>
        {
            // 过滤遮罩
            if (item.label.includes("mask"))
            {
                // 找到当前遮罩的精灵图
                const sprite = item.children?.find((itemChild: Sprite | Graphics) =>
                {
                    return itemChild.label && itemChild.label.includes(item.label);
                });

                if (sprite)
                {
                    // 获取当前遮罩的Canvas
                    const canvas = (item as any)?.metadata?.canvas;

                    // 获取当前遮罩是否激活
                    const active = (item as any)?.metadata?.active;

                    // 获取当前遮罩的Canvas上下文
                    const ctx = canvas?.getContext("2d", {willReadFrequently: true});

                    if (!canvas || !ctx)
                    {
                        return;
                    }

                    // 获取像素数据
                    const pixelData = ctx.getImageData(localPos.x * scale, localPos.y * scale, 1, 1).data;

                    if (pixelData[3] > 0)
                    {
                        fn && fn.apply(item, [{label: item.label, container: item, sprite: sprite, active: active}]);
                    }
                }
            }
        });
    }
}

export default CanvasDistrict;